package com.ruoyi.livedemo.controller;

import com.ruoyi.livedemo.common.ApiResponse;
import com.ruoyi.livedemo.context.CurrentUserHolder;
import com.ruoyi.livedemo.dto.FileMetadataResponse;
import com.ruoyi.livedemo.entity.Attachment;
import com.ruoyi.livedemo.service.FileStorageService;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/files")
public class FileController {

    private final FileStorageService fileStorageService;

    @PostMapping
    public ApiResponse<FileMetadataResponse> upload(@RequestPart("file") MultipartFile file,
                                                    @RequestParam(value = "description", required = false) String description) {
        Long userId = CurrentUserHolder.getUserId();
        FileMetadataResponse metadata = fileStorageService.store(userId, file, description);
        return ApiResponse.ok("文件上传成功", metadata);
    }

    @GetMapping("/{id}")
    public ApiResponse<FileMetadataResponse> metadata(@PathVariable Long id) {
        Long userId = CurrentUserHolder.getUserId();
        Attachment attachment = fileStorageService.findMetadata(userId, id);
        return ApiResponse.ok(toResponse(attachment));
    }

    @GetMapping("/{id}/download")
    public ResponseEntity<Resource> download(@PathVariable Long id) {
        Long userId = CurrentUserHolder.getUserId();
        Attachment attachment = fileStorageService.findMetadata(userId, id);
        Resource resource = fileStorageService.loadAsResource(userId, id);
        String filename = Paths.get(attachment.getFilePath()).getFileName().toString();
        String encodedName = UriUtils.encode(filename, StandardCharsets.UTF_8);
        String mediaType = attachment.getMediaType() != null ? attachment.getMediaType() : MediaType.APPLICATION_OCTET_STREAM_VALUE;
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(mediaType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedName)
                .body(resource);
    }

    private FileMetadataResponse toResponse(Attachment attachment) {
        return new FileMetadataResponse(
                attachment.getId(),
                attachment.getFilePath(),
                attachment.getMediaType(),
                attachment.getSizeBytes(),
                attachment.getCreatedAt()
        );
    }
}
